package com.deer.wms.instock.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deer.wms.ASN.manage.model.asn.AsnData;
import com.deer.wms.ASN.manage.model.asn.AsnDetail;
import com.deer.wms.ASN.manage.model.asn.AsnMaster;
import com.deer.wms.ASN.manage.service.AsnMasterService;
import com.deer.wms.instock.dao.AllotMasterMapper;
import com.deer.wms.instock.model.Allot.AllotData;
import com.deer.wms.instock.model.Allot.AllotDetail;
import com.deer.wms.instock.model.Allot.AllotMaster;
import com.deer.wms.instock.model.Allot.AllotMasterCriteria;
import com.deer.wms.instock.service.AllotDetailService;
import com.deer.wms.instock.service.AllotMasterService;
import com.deer.wms.intercept.common.data.CurrentUser;
import com.deer.wms.project.root.service.SuperServiceImpl;
import com.deer.wms.project.root.util.BeanUtils;
import com.deer.wms.project.root.util.DateUtils;
import com.deer.wms.review.manage.model.BillRecord;
import com.deer.wms.review.manage.service.BillRecordService;
import com.deer.wms.review.manage.service.CaseMasterService;
import com.deer.wms.system.manage.model.address.ShippingAddress;
import com.deer.wms.system.manage.model.carrier.Carrier;
import com.deer.wms.system.manage.service.CarrierService;
import com.deer.wms.system.manage.service.ShippingAddressService;
import com.deer.wms.system.manage.service.ValidatorService;
import com.deer.wms.ware.task.model.SO.SoData;
import com.deer.wms.ware.task.model.SO.SoDetail;
import com.deer.wms.ware.task.model.SO.SoMaster;
import com.deer.wms.ware.task.service.SoMasterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ll on 2020/03/04.
 */
@Service
@Transactional
public class AllotMasterServiceImpl extends SuperServiceImpl<AllotMasterMapper, AllotMaster> implements AllotMasterService {

    @Autowired
    private AllotMasterMapper allotMasterMapper;

    @Autowired
    private AllotMasterService allotMasterService;

    @Autowired
    private AllotDetailService allotDetailService;

    @Autowired
    private ValidatorService validatorService;

    @Autowired
    private CaseMasterService caseMasterService;

    @Autowired
    private AsnMasterService asnMasterService;

    @Autowired
    private SoMasterService soMasterService;

    @Autowired
    private CarrierService carrierService;

    @Autowired
    private ShippingAddressService shippingAddressService;

    @Autowired
    private BillRecordService billRecordService;


    @Override
     public List<AllotMaster> findList(AllotMasterCriteria criteria){
        return allotMasterMapper.findList(criteria);
    }

    @Override
    public void createAllotMaster(AllotData allotData, CurrentUser currentUser) {

        AllotMaster allotMaster = allotData.getAllotMaster();
        String tableName = "allot_master";
        Integer nextId = validatorService.getNextId(tableName);
        String billNo = "DB" + "-" + nextId;
        Integer createUserId = currentUser.getUserId();
        String createUserName = currentUser.getUserName();
        String createTime = DateUtils.getNowDateTimeString();

        //添加调拨单跟踪信息
        BillRecord billRecord = new BillRecord();
        billRecord.setBillNo(billNo);
        billRecord.setRecordType(38);//调拨新增
        billRecord.setCreateTime(createTime);
        billRecord.setCreateUserId(createUserId);
        billRecord.setCreateUserName(createUserName);
        billRecordService.createBillRecord(billRecord, currentUser);

        //状态   2-等待审核(初始化)  1-审核通过  0-审核中  -1-审核退回
        Integer state = 2;
        /**
         * 创建方式为草稿
         */
        if (allotData.getInsertType() == -2) {
            state = 2;
            BillRecord billRecord1 = new BillRecord();
            billRecord1.setBillNo(billNo);
            billRecord1.setRecordType(39);//调拨草稿
            billRecord1.setCreateTime(createTime);
            billRecord1.setCreateUserId(createUserId);
            billRecord1.setCreateUserName(createUserName);
            billRecordService.createBillRecord(billRecord1, currentUser);
        }
        /**
         * 提交
         */
        else if (allotData.getInsertType() == 0) {
            String billNo1 = allotData.getAllotMaster().getBillNo();
            //通过草稿提交，则需要先把草稿删掉
            if (billNo1 != null) {
                asnMasterService.deleteByBillNo(billNo1);
                BillRecord billRecord1 = billRecordService.findByBillNoAndType(billNo, 39);//调拨草稿
                billRecord1.setModifyTime(DateUtils.getNowDateTimeString());
                billRecord1.setModifyUserId(currentUser.getUserId());
                billRecord1.setModifyUserName(currentUser.getUserName());
                billRecordService.updateById(billRecord1);
            }
            /**
             * 添加审核流
             */
            //        -1不通过  0-流转中 1-已通过
            state = caseMasterService.createCase(billNo, 2, currentUser.getUserId(), allotMaster.getFromWareId(), allotMaster.getOrganizationId());
            BillRecord billRecord1 = new BillRecord();
            billRecord1.setBillNo(billNo);
            billRecord1.setRecordType(40);//调拨审核
            billRecord1.setCreateTime(createTime);
            billRecord1.setCreateUserId(createUserId);
            billRecord1.setCreateUserName(createUserName);
            billRecordService.createBillRecord(billRecord1, currentUser);
            if (state == 1) {
                billRecord1.setModifyTime(DateUtils.getNowDateTimeString());
                billRecord1.setModifyUserId(createUserId);
                billRecord1.setModifyUserName(createUserName);
                billRecordService.updateById(billRecord1);
            }

        }

        //保存调拨单表头信息
        allotMaster.setCreateUserId(createUserId);
        allotMaster.setCreateUserName(createUserName);
        allotMaster.setCreateTime(createTime);
        allotMaster.setBillNo(billNo);
        allotMaster.setCaseState(state);
        allotMaster.setInsertType(allotData.getInsertType());
        allotMasterService.save(allotMaster);

        //保存调拨单明细信息
        List<AllotDetail> allotDetails = allotData.getAllotDetails();
        for (int i = 0; i < allotDetails.size(); i++) {
            String detailNo = billNo + "-" + (i + 1);
            AllotDetail allotDetail = allotDetails.get(i);
            allotDetail.setBillNo(billNo);
            allotDetail.setDetailNo(detailNo);
            allotDetailService.save(allotDetail);
        }
        BillRecord billRecord1 = billRecordService.findByBillNoAndType(billNo, 38);//调拨新增
        billRecord1.setModifyTime(DateUtils.getNowDateTimeString());
        billRecord1.setModifyUserId(createUserId);
        billRecord1.setModifyUserName(createUserName);
        billRecordService.updateById(billRecord1);
    }

    @Override
    public void deleteByBillNo(String billNo) {
        allotMasterMapper.deleteByBillNo(billNo);
    }

    @Override
    public AllotMaster findBy(String field, String value) {
        QueryWrapper<AllotMaster> qw = new QueryWrapper<>();
        return getOne(qw.eq(field, value));
    }

    @Override
    public void createAsnBill(AllotData allotData, CurrentUser currentUser){
        //生成ASN单
        Integer createUserId = currentUser.getUserId();
        String createUserName = currentUser.getUserName();
        String createTime = DateUtils.getNowDateTimeString();
        BillRecord billRecord =new BillRecord();
        billRecord.setBillNo(allotData.getAllotMaster().getBillNo());
        billRecord.setRecordType(41);//生成ASN
        billRecord.setCreateTime(createTime);
        billRecord.setCreateUserId(createUserId);
        billRecord.setCreateUserName(createUserName);
        billRecordService.createBillRecord(billRecord,currentUser);

        AsnData asnData = new AsnData();
        asnData.setBillSource(4);//调拨生成
        asnData.setInsertType(0);//提交
        AsnMaster asnMaster = new AsnMaster();
        BeanUtils.copyProperties(allotData.getAllotMaster(),asnMaster);
        asnMaster.setBillNo(null);
        asnMaster.setWareId(allotData.getAllotMaster().getToWareId());
        asnMaster.setWareName(allotData.getAllotMaster().getToWareName());
        asnMaster.setAllotBillNo(allotData.getAllotMaster().getBillNo());
        asnMaster.setAsnType(24);
        Carrier carrier = carrierService.getById(allotData.getAllotMaster().getCarrierId());
        asnMaster.setCarrierCode(carrier.getCarrierCode());
        ShippingAddress shippingAddress = shippingAddressService.findByThree(allotData.getAllotMaster().getOrganizationId(),allotData.getAllotMaster().getFromWareId(),1);
        //发货地
        if(shippingAddress==null){
            asnMaster.setLoadingPlace(null);
        }else {
            asnMaster.setLoadingPlace(shippingAddress.getProvince()+ shippingAddress.getCity()+shippingAddress.getArea()+shippingAddress.getDetailAddress());
        }
        ShippingAddress shippingAddress1 = shippingAddressService.findByThree(allotData.getAllotMaster().getOrganizationId(),allotData.getAllotMaster().getToWareId(),1);
        //交货地
        if(shippingAddress1==null){
            asnMaster.setDeliveryPlace(null);
        }else {
            asnMaster.setDeliveryPlace(shippingAddress1.getProvince()+ shippingAddress1.getCity()+shippingAddress1.getArea()+shippingAddress1.getDetailAddress());
        }
        asnData.setAsnMaster(asnMaster);
        List<AsnDetail> details = new ArrayList<>();
        for(AllotDetail allotDetail :allotData.getAllotDetails()){
            AsnDetail asnDetail = new AsnDetail();
            BeanUtils.copyProperties(allotDetail,asnDetail);
            asnDetail.setAllotDetailNo(allotDetail.getDetailNo());
            asnDetail.setItemCode(allotDetail.getItemCode());
            asnDetail.setItemName(allotDetail.getItemName());
            asnDetail.setPackDetailId(allotDetail.getPackDetailId());
            asnDetail.setPackDescribe(allotDetail.getPackDescribe());
            asnDetail.setTransRatio(allotDetail.getTransRatio());
            asnDetail.setQcState(1);//合格
            asnDetail.setBillNo(null);
            asnDetail.setDetailNo(null);
            details.add(asnDetail);
        }
        asnData.setAsnDetails(details);
        asnMasterService.createAsnMaster(asnData,currentUser);

        //生成SO单
        SoData soData = new SoData();
        soData.setBillSource(3);//调拨生成
        soData.setInsertType(0);//提交
        BillRecord billRecord1 =new BillRecord();
        billRecord1.setBillNo(allotData.getAllotMaster().getBillNo());
        billRecord1.setRecordType(42);//生成SO
        billRecord1.setCreateTime(createTime);
        billRecord1.setCreateUserId(createUserId);
        billRecord1.setCreateUserName(createUserName);
        billRecordService.createBillRecord(billRecord1,currentUser);

        SoMaster soMaster = new SoMaster();
        BeanUtils.copyProperties(allotData.getAllotMaster(),soMaster);
        soMaster.setBillNo(null);
        soMaster.setAllotBillNo(allotData.getAllotMaster().getBillNo());
        soMaster.setWareId(allotData.getAllotMaster().getFromWareId());
        soMaster.setWareName(allotData.getAllotMaster().getFromWareName());
        soMaster.setSoType(30);
        soData.setSoMaster(soMaster);

        List<SoDetail>soDetails = new ArrayList<>();

        for(AllotDetail allotDetail :allotData.getAllotDetails()){
            SoDetail soDetail = new SoDetail();
            BeanUtils.copyProperties(allotDetail,soDetail);
            soDetail.setAllotDetailNo(allotDetail.getDetailNo());
            soDetail.setOrderQuantity(allotDetail.getExpectQuantity());
            soDetail.setBillNo(null);
            soDetail.setDetailNo(null);
            soDetails.add(soDetail);
        }
        soData.setSoDetails(soDetails);
        soMasterService.createSoMaster(soData,currentUser);

        AllotMaster allotMaster = allotData.getAllotMaster();
        allotMaster.setState(2);//全部调拨
        allotMasterService.updateById(allotMaster);
        List<AllotDetail> allotDetails = allotData.getAllotDetails();
        for(AllotDetail allotDetail :allotDetails){
            allotDetail.setState(2);//全部调拨
            allotDetailService.updateById(allotDetail);
        }
    }
}
